package com.top.application.utils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class HMACmd5 {
	/**
	 * MAC算法可选以下多种算法 HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512
	 */
	public static final String KEY_MAC = "HmacMD5";

	/**
	 * HMAC加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptHmacMD5(String data, String key)
			throws Exception {
		SecretKey secretKey = new SecretKeySpec(key.getBytes(), KEY_MAC);
		Mac mac = Mac.getInstance(secretKey.getAlgorithm());
		mac.init(secretKey);
		byte[] macBytes = mac.doFinal(data.getBytes());
		StringBuffer sb = new StringBuffer(macBytes.length * 2);
		for (int i = 0; i < macBytes.length; i++) {
			int v = macBytes[i] & 0xff;
			if (v < 16) {
				sb.append('0');
			}
			sb.append(Integer.toHexString(v));
		}
		return sb.toString();
	}

	/**
	 * @Title: main
	 * @Description: TODO测试案例)
	 * @param @param args
	 * @param @throws Exception 设定文件
	 * @author zhaiey
	 * @return void 返回类型
	 * @throws
	 */
	public static void main(String[] args) throws Exception {
		String inputStr = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ0ZXN0IjoiZGVtb24iLCJpc3MiOiJhdXRoMCIsInRlc3QxIjoiZGVtb24xIiwiemhhaSI6ImVyeXVhbiJ9.NAxbCzQXYQEiL2eRt9b5L4ahmbRQth6MKF-xpi3wzLAIK-r1UtFevR1ZjIcyqoJWv3yIf7ROLB_4U643DJmJMecqp-Z0TNkb7LrJsLo1YiZIUSwY2J-vLP36bCM0JxOPSABE5cbhHi44KnbGyAoU87n7kueEdPOr-ITR2_aiKz6Ah3JKzgMQvrLBnjWB41t2tcKkx7UEZlHtqDI7lx8pi5y-ZEFIVKqSsXNX9sIohHkDF5Z1BF_pdxozXNVnImyn7fkAVtGFPLPu7GM759ZLolcoOEecARfIBBXKemGktBwuOs099VRDG4CRES9TG1AkoRGN8YEXqC1JpV0VAGePXQ";
		String key = "somekey";
		System.out.println(HMACmd5.encryptHmacMD5(inputStr, key));
	}
}
